/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package helper;

import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import model.Member1Facade;

/**
 *
 * @author shinji
 */
@FacesValidator(value = "Validation.Birthday")
public class Validation_Birthday implements Validator{
    Member1Facade member1Facade = lookupMember1FacadeBean();

    private Member1Facade lookupMember1FacadeBean() {
        try {
            Context c = new InitialContext();
            return (Member1Facade) c.lookup("java:global/Matrimony/Matrimony-ejb/Member1Facade!model.Member1Facade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        Date Birthday = (Date)value;
        
        try {
            int Age = 0;

            //get Age
            if (Birthday != null) {
                Date now = new Date();
                Age = now.getYear() - Birthday.getYear();
            }

            if (Age < 18)
                set_message(FacesMessage.SEVERITY_ERROR, "Check Birthday", "You have more than 18 age !!!");
            

        } catch (Exception e) {
        }
    }
    
    // <editor-fold defaultstate="collapsed" desc=" Set message ">
    private void set_message(FacesMessage.Severity severity, String title, String message) {
        try {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(severity, title, message));

        } catch (Exception e) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "Error message !!!"));
        }
    }
    // </editor-fold> 
}
